package com.test.core;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;

import javax.imageio.ImageIO;

import com.test.dao.PostDAO;
import com.test.objects.Author;
import com.test.objects.Category;
import com.test.objects.MyPageException;
import com.test.objects.Post;
import com.test.objects.PostClass;

public class PostService {
	private PostDAO postDAO;
	private String appLocation = "";
	
	public void setPostDAO(PostDAO _postDAO){
		this.postDAO = _postDAO;
	}
	
	public void setAppLocation(String appLocation){
		this.appLocation = appLocation;
	}
	
	public Post[] getPostList(){
		int maxRow = 10;
		return this.postDAO.getAllPosts(maxRow);
	}
	
	public Post[] getPostList(int startRow, int numRow){
		return this.postDAO.getAllPosts(startRow, numRow);
	}
	
	public Post[] getPostList(PostClass pc, 
			int id, int startRow, int numRow){
		return this.postDAO.getAllPosts(pc, id, startRow, numRow);
	}
	
	public Post getPost(int id) {
		try {
			return this.postDAO.getPost(id);
		}catch(MyPageException mpEx){
			return null;
		}
	}
	
	public int getPostCount(){
		return this.postDAO.getNumPost();
	}
	
	public int getPostCount(PostClass pc, int id){
		return this.postDAO.getNumPost(pc, id);
	}
	
	public Category getCategory(int catId){
		return this.postDAO.getCategory(catId);
	}
	
	public Category[] getCategories(){
		return this.postDAO.getCategories();
	}
	
	public Author getAuthor(int authorId){
		return this.postDAO.getAuthor(authorId);
	}
	
	public int savePost(Post post) throws MyPageException {
		Post newPost = post;
		if (!post.getImageUrl().equals("")){
			String newImageUrl = resizeImage(post.getImageUrl());
			newPost.setImageUrl(newImageUrl);
		}
		return this.postDAO.savePost(newPost);
	}
	
	private String resizeImage(String imgUrl) throws MyPageException {
		String subImageFolder = "/images/s_img";
		try {
			BufferedImage srcImg = ImageIO.read(new URL(imgUrl));
			int w = srcImg.getWidth(), h = srcImg.getHeight();
			int new_w = 135;
			int new_h = (int)((float)new_w * (float)h / (float)w);
			BufferedImage destImg = new BufferedImage(
							new_w, new_h, srcImg.getType());
			Graphics2D g = destImg.createGraphics();
			g.drawImage(srcImg, 0, 0, new_w, new_h, null);
			g.dispose();
			String imgExt = imgUrl.substring(imgUrl.lastIndexOf(".") + 1);
			String newImgPath = subImageFolder + 
						UUID.randomUUID().toString() + "." + imgExt;
			ImageIO.write(destImg, imgExt, new File(this.appLocation + newImgPath));
			return "." + newImgPath;
		}catch(IOException ioEx){
			throw new MyPageException(
				"can not resize the quick-view image " + 
				"(io exception: " + ioEx.getMessage() + ")");
		}
	}
	
	public int deletePost(int id) throws MyPageException {
		return this.postDAO.deletePost(id);
	}
}
